package com.qixin.modules.eaApplication.controller;

import java.io.UnsupportedEncodingException;
import java.io.IOException;
import java.net.URLDecoder;
import java.util.*;
import java.util.stream.Collectors;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.qixin.modules.ea.vo.ListPageVo;
import com.qixin.modules.eaApplication.entity.EaEntertainApply;
import com.qixin.modules.eaApplication.mapper.EaEntertainChangeMapper;
import com.qixin.modules.eaBasic.vo.EaTaskVo;
import com.qixin.modules.eaBasic.vo.IdVo;
import org.jeecg.common.util.EmptyUtil;
import org.jeecgframework.poi.excel.ExcelImportUtil;
import org.jeecgframework.poi.excel.def.NormalExcelConstants;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.entity.ImportParams;
import org.jeecgframework.poi.excel.view.JeecgEntityExcelView;
import org.jeecg.common.system.vo.LoginUser;
import org.apache.shiro.SecurityUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.util.oConvertUtils;
import com.qixin.modules.eaApplication.entity.EaHostObject;
import com.qixin.modules.eaApplication.entity.EaEntertainChange;
import com.qixin.modules.eaApplication.vo.EaEntertainChangePage;
import com.qixin.modules.eaApplication.service.IEaEntertainChangeService;
import com.qixin.modules.eaApplication.service.IEaHostObjectService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;
import com.alibaba.fastjson.JSON;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.jeecg.common.aspect.annotation.AutoLog;

 /**
 * @Description: 招待费申请变更单
 * @Author: qixin-boot
 * @Date:   2021-07-06
 * @Version: V1.0
 */
@Api(tags="招待费申请变更单")
@RestController
@RequestMapping("/eaApplication/eaEntertainChange")
@Slf4j
public class EaEntertainChangeController {
	@Autowired
	private IEaEntertainChangeService eaEntertainChangeService;
	@Autowired
	private IEaHostObjectService eaHostObjectService;
	@Autowired
	private EaEntertainChangeMapper eaEntertainChangeMapper;

	 /**
	  * 查询招待费申请变更单信息列表
	  *
	  * @param listPageVo
	  * @return Result
	  */
	 @ApiOperation(value="招待费申请变更单信息列表-查询", notes="招待费申请变更单信息列表-查询")
	 @PostMapping(value = "/list")
	 public Result<?> list(@RequestBody ListPageVo listPageVo) {
		 Map<String,Object> resutlList = eaEntertainChangeService.list(listPageVo);
		 return Result.OK(resutlList);
	 }

	 /**
	  * 编辑招待费申请变更单信息
	  *
	  * @param eaEntertainChangePage
	  * @return
	  */
	 @AutoLog(value = "招待费申请变更单信息-编辑")
	 @ApiOperation(value="招待费申请变更单信息-编辑", notes="招待费申请变更单信息-编辑")
	 @PostMapping(value = "/edit")
	 public Result<?> edit(@RequestBody EaEntertainChangePage eaEntertainChangePage) {
		 EaEntertainChange eaEntertainChange = new EaEntertainChange();
		 BeanUtils.copyProperties(eaEntertainChangePage, eaEntertainChange);
		 EaEntertainChange eaEntertainChangeEntity = eaEntertainChangeService.getById(eaEntertainChange.getId());
		 if(eaEntertainChangeEntity==null) {
			 return Result.error("未找到对应数据");
		 }

		 //判断单据是否已经被提交
		 EaEntertainChange eaEntertainChange1 = eaEntertainChangeService.getById(eaEntertainChangePage.getId());
		 String status = EmptyUtil.checkNull(eaEntertainChange1.getBillStatus());   //当状态为1审批中,2已审批时,提示单据状态已变更,请刷新
		 if(status.equals("1") || status.equals("2")){
			 return Result.error("单据状态已变更,请刷新");
		 }

		 eaEntertainChange.setSaveType("add");    //保存
		 Map<String,Object> returnMap = eaEntertainChangeService.updateMain(eaEntertainChange,eaEntertainChangePage.getEaHostObjectList(),eaEntertainChangePage.getEaEntertainReceptionActivities());

		 if(returnMap.get("code").equals("-1")){
			 return Result.error(EmptyUtil.checkNull(returnMap.get("message")));
		 }else{
			 returnMap.remove("code");
			 returnMap.remove("message");
			 return Result.OK(returnMap);
		 }
	 }

	 /**
	  * 招待费申请变更单审批/退回
	  *
	  * @param eaTaskVo
	  * @return
	  */
	 @AutoLog(value = "招待费申请变更单审批/退回")
	 @ApiOperation(value="招待费申请变更单审批/退回", notes="招待费申请变更单审批/退回")
	 @PostMapping(value = "/audit")
	 public Result<?> edit(@RequestBody EaTaskVo eaTaskVo) {
		 Map<String,Object> returnMap = eaEntertainChangeService.audit(eaTaskVo);
		 return Result.OK(returnMap);
	 }

	/**
	 *   通过id删除
	 *
	 * @param id
	 * @return
	 */
	@AutoLog(value = "招待费申请变更单-通过id删除")
	@ApiOperation(value="招待费申请变更单-通过id删除", notes="招待费申请变更单-通过id删除")
	@DeleteMapping(value = "/delete")
	public Result<?> delete(@RequestParam(name="id",required=true) String id) {
		eaEntertainChangeService.delMain(id);
		return Result.OK("删除成功!");
	}

	/**
	 *  批量删除
	 *
	 * @param ids
	 * @return
	 */
	@AutoLog(value = "招待费申请变更单-批量删除")
	@ApiOperation(value="招待费申请变更单-批量删除", notes="招待费申请变更单-批量删除")
	@DeleteMapping(value = "/deleteBatch")
	public Result<?> deleteBatch(@RequestParam(name="ids",required=true) String ids) {
		this.eaEntertainChangeService.delBatchMain(Arrays.asList(ids.split(",")));
		return Result.OK("批量删除成功！");
	}

	 /**
	  * 查询招待费申请变更单详情
	  *
	  * @param idVo
	  * @return
	  */
	 @ApiOperation(value="招待费申请变更单详情-查询", notes="招待费申请变更单详情-查询")
	 @PostMapping(value = "/selectById")
	 public Result<?> selectById(@RequestBody IdVo idVo) {
		 String id = idVo.getId();
		 EaEntertainChange eaEntertainChange = eaEntertainChangeMapper.selectById(id);
		 if(eaEntertainChange==null) {
			 return Result.error("未找到对应数据");
		 }
		 Map<String, Object> resutlList = eaEntertainChangeService.selectById(id);
		 return Result.OK(resutlList);
	 }


	/**
	 * 通过id查询
	 *
	 * @param id
	 * @return
	 */
	@ApiOperation(value="招待费申请变更单-通过id查询", notes="招待费申请变更单-通过id查询")
	@GetMapping(value = "/queryById")
	public Result<?> queryById(@RequestParam(name="id",required=true) String id) {
		EaEntertainChange eaEntertainChange = eaEntertainChangeService.getById(id);
		if(eaEntertainChange==null) {
			return Result.error("未找到对应数据");
		}
		return Result.OK(eaEntertainChange);

	}

	 /**
	  * 通过id修改状态
	  *
	  * @param id
	  * @return
	  */
	 @AutoLog(value = "招待费申请变更单-通过id修改状态")
	 @ApiOperation(value="招待费申请变更单-通过id修改状态", notes="招待费申请变更单-通过id修改状态")
	 @GetMapping(value = "/updateState")
	 public Result<?> updateState(@RequestParam(name="id",required=true) String id ,@RequestParam(name = "billStatus",required = true) Integer billStatus) {
		 EaEntertainChange eaEntertainChange = eaEntertainChangeService.getById(id);
		 eaEntertainChange.setBillStatus(billStatus);
		 eaEntertainChangeService.updateById(eaEntertainChange);
		 return Result.OK("修改状态成功");

	 }

	/**
	 * 通过id查询
	 *
	 * @param id
	 * @return
	 */
	@ApiOperation(value="招待对象明细表主表ID查询", notes="招待对象明细表-通主表ID查询")
	@GetMapping(value = "/queryEaHostObjectByMainId")
	public Result<?> queryEaHostObjectListByMainId(@RequestParam(name="id",required=true) String id) {
		List<EaHostObject> eaHostObjectList = eaHostObjectService.selectByMainId(id);
		return Result.OK(eaHostObjectList);
	}

    /**
    * 导出excel
    *
    * @param request
    * @param eaEntertainChange
    */
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, EaEntertainChange eaEntertainChange) {
      // Step.1 组装查询条件查询数据
      QueryWrapper<EaEntertainChange> queryWrapper = QueryGenerator.initQueryWrapper(eaEntertainChange, request.getParameterMap());
      LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();

      //Step.2 获取导出数据
      List<EaEntertainChange> queryList = eaEntertainChangeService.list(queryWrapper);
      // 过滤选中数据
      String selections = request.getParameter("selections");
      List<EaEntertainChange> eaEntertainChangeList = new ArrayList<EaEntertainChange>();
      if(oConvertUtils.isEmpty(selections)) {
          eaEntertainChangeList = queryList;
      }else {
          List<String> selectionList = Arrays.asList(selections.split(","));
          eaEntertainChangeList = queryList.stream().filter(item -> selectionList.contains(item.getId())).collect(Collectors.toList());
      }

      // Step.3 组装pageList
      List<EaEntertainChangePage> pageList = new ArrayList<EaEntertainChangePage>();
      for (EaEntertainChange main : eaEntertainChangeList) {
          EaEntertainChangePage vo = new EaEntertainChangePage();
          BeanUtils.copyProperties(main, vo);
          List<EaHostObject> eaHostObjectList = eaHostObjectService.selectByMainId(main.getId());
          vo.setEaHostObjectList(eaHostObjectList);
          pageList.add(vo);
      }

      // Step.4 AutoPoi 导出Excel
      ModelAndView mv = new ModelAndView(new JeecgEntityExcelView());
      mv.addObject(NormalExcelConstants.FILE_NAME, "招待费申请变更单列表");
      mv.addObject(NormalExcelConstants.CLASS, EaEntertainChangePage.class);
      mv.addObject(NormalExcelConstants.PARAMS, new ExportParams("招待费申请变更单数据", "导出人:"+sysUser.getRealname(), "招待费申请变更单"));
      mv.addObject(NormalExcelConstants.DATA_LIST, pageList);
      return mv;
    }

    /**
    * 通过excel导入数据
    *
    * @param request
    * @param response
    * @return
    */
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
      MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
      Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
      for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
          MultipartFile file = entity.getValue();// 获取上传文件对象
          ImportParams params = new ImportParams();
          params.setTitleRows(2);
          params.setHeadRows(1);
          params.setNeedSave(true);
          try {
              List<EaEntertainChangePage> list = ExcelImportUtil.importExcel(file.getInputStream(), EaEntertainChangePage.class, params);
              for (EaEntertainChangePage page : list) {
                  EaEntertainChange po = new EaEntertainChange();
                  BeanUtils.copyProperties(page, po);
                  eaEntertainChangeService.saveMain(po, page.getEaHostObjectList(),page.getEaEntertainReceptionActivities());
              }
              return Result.OK("文件导入成功！数据行数:" + list.size());
          } catch (Exception e) {
              log.error(e.getMessage(),e);
              return Result.error("文件导入失败:"+e.getMessage());
          } finally {
              try {
                  file.getInputStream().close();
              } catch (IOException e) {
                  e.printStackTrace();
              }
          }
      }
      return Result.OK("文件导入失败！");
    }

}
